<template>
  <div class="login-no-test">
    <LayOutLogin form-title-name="登录" @isDingTalk="isDingTalk" @handle-click-ding="handleClickDing">
      <template v-slot:form v-if="isShowDingTalk">
        <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :class="isShowCaptcha ? 'form-box' : ''">
          <FormItem prop="userAccount" class="form-item-user">
            <i-input
              type="text"
              style="width: 100%"
              placeholder="请输入账号/手机号/邮箱"
              v-model="formValidate.userAccount"
            >
            </i-input>
          </FormItem>
          <FormItem class="form-item-password" prop="password">
            <i-input
              type="password"
              style="width: 100%"
              placeholder="请输入密码"
              password
              @on-enter="login('formValidate')"
              v-model="formValidate.password">
            </i-input>
          </FormItem>
          <FormItem class="form-item-other">
            <template v-if="isShowAutoLogin">
              <Checkbox
                key="showAutoLogin"
                :true-value="true"
                :false-value="false"
                v-model="isRemember">
                <span>记住密码</span>
              </Checkbox>
            </template>
            <template v-else>
              <span key="noShowAutoLogin"></span>
            </template>
            <span
              style="cursor: pointer"
              @click="handleRouterOperate('/forgetCode')"
              v-if="isShowForgetCode"
            >忘记密码？</span>
          </FormItem>
          <FormItem class="ivu-form-btn">
            <Button
              type="primary"
              :loading="loading"
              long
              style="background-color: #2878FF"
              @click="login('formValidate')">登录
            </Button>
          </FormItem>
          <FormItem class="form-other-login">
            <span @click="handleRouterOperate('/loginP')" v-if="isShowPhone">验证码登录</span>
            <span @click="handleRouterOperate()" v-if="isShowRegister">注册</span>
          </FormItem>
        </Form>
      </template>
    </LayOutLogin>
    <Modal
      v-model="viewParams.flag"
      :title="viewParams.title"
      :mask-closable="false"
      width="70"
      cancel-text="不再提示"
      :closable="false"
      ok-text="关闭"
      @on-cancel="handleCancelModal"
    >
      <p style="color: #BEBEBE">有新的版本发布,为了获得最佳体验,请及时清理缓存</p>
      <p style="color: #BEBEBE">使用快捷键: Ctrl + Shift + Delete可快速清理浏览器缓存</p>
      <p style="font-weight: bold">本次更新内容如下 : </p>
      <Row>
        <i-col :span="24" v-for="(item,index) in contentArr" :key="index + 'view'">{{item}}</i-col>
      </Row>
    </Modal>
    <Modal
      v-model="tsetViewParams.flag"
      title="安全验证"
      :footer-hide="true"
      width="310px"
      class="verification-model"
     >
      <slide-verify
        :key="tsetViewParams.flag"
        :l="42"
        :r="10"
        :w="310"
        :h="170"
        :imgs="imags"
        slider-text="向右滑动"
        @success="onSuccess"
        ></slide-verify>
    </Modal>
  </div>
</template>

<script>
import { login, getRsaPublicKey, dingTalkQrLogin, weChatLogin } from '../../api/modules/login/login'
import { cookieData, getCookieItem, setCookieItem } from '../../utils/cookie'
import message from '../../utils/message'
import COOKIE_KEY from '../../config/cookie'
import { decrypt, encrypt } from '../../utils/encrypt'
import { typeOf } from '../../utils/verification'
// import SIdentify from '@/components/code/identify'
import { getNewVersion } from '../../api/modules/system-log/version'
import { JSEncrypt } from 'jsencrypt'
import imgs from '../../../public/img/google.png'
import { saveLoginInfo } from '../../api/modules/login/saveLoginInfo'
import { goLogin } from '../../router'
import { mapMutations, mapGetters } from 'vuex'
import STATE_KEY from '../../config/store'
export default {
  name: 'LoginDefault',
  data () {
    return {
      imags: [require('@/assets/imgs/login/img.jpg'), require('@/assets/imgs/login/img1.jpg'), require('@/assets/imgs/login/img2.jpg'), require('@/assets/imgs/login/img3.jpg'), require('@/assets/imgs/login/img4.jpg'), require('@/assets/imgs/login/img5.jpg')],
      formValidate: {
        userAccount: '',
        rsaKey: '',
        siteCode: 'manage',
        loginType: '0',
        password: ''
      },
      publicKey: '',
      ruleValidate: {
        userAccount: [{ required: true, message: '账号不能为空', trigger: 'change' }],
        password: [{ required: true, message: '密码不能为空', trigger: 'change' },
          { min: 6, trigger: 'change', message: '密码不能少于6位数' }]
      },
      loading: false,
      isShowCaptcha: false,
      captchaText: '点击获取验证码',
      isGetCaptcha: false,
      timeId: null,
      countdownTime: 60,
      isRemember: false,
      // identifyCodes: '1234567890ABCDEFGHIJKLMNOPQRSTUVWSYZabcdefghijklmnopqrstuvwsyz',
      // identifyCode: '',
      msg: '',
      text: '向右滑',
      codeIsShow: false,
      viewParams: {
        flag: false,
        title: ''
      },
      contentArr: [],
      isShowDingTalk: true,
      tsetViewParams: {
        flag: false
      },
      nailedFormValidate: {
        code: '',
        state: ''
      },
      weChatFormValidate: {
        code: '',
        state: ''
      },
      isClickDing: false
    }
  },
  created () {
    this.privateInit()
  },
  mounted () {
    var browser = {
      versions: (function () {
        var u = navigator.userAgent
        // var app = navigator.appVersion
        return {
          trident: u.indexOf('Trident') > -1, // IE内核
          presto: u.indexOf('Presto') > -1, // opera内核
          webKit: u.indexOf('AppleWebKit') > -1, // 苹果、谷歌内核
          gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') === -1, // 火狐内核
          mobile: !!u.match(/AppleWebKit.*Mobile.*/), // 是否为移动终端
          ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), // ios终端
          android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, // android终端
          iPhone: u.indexOf('iPhone') > -1, // 是否为iPhone或者QQHD浏览器
          iPad: u.indexOf('iPad') > -1, // 是否iPad
          webApp: u.indexOf('Safari') === -1, // 是否web应该程序，没有头部与底部
          weixin: u.indexOf('MicroMessenger') > -1, // 是否微信 （2015-01-22新增）
          qq: u.match(/\sQQ/i) === ' qq' // 是否QQ
        }
      }()),
      language: (navigator.browserLanguage || navigator.language).toLowerCase()
    }
    if (browser.versions.trident) {
      this.$Notice.warning({
        duration: 0,
        render: h => {
          return h('div', [
            h('h4', '为了给您良好的用户体验'),
            h('h3', '强烈建议使用以下版本浏览器', {
              style: 'margin-top:8px'
            }),
            h('img', {
              attrs: {
                src: imgs,
                style: 'width:30px;margin-top:8px'
              }
            })
          ])
        }
      })
    }
  },
  computed: {
    // 是否显示注册
    isShowRegister () {
      return process.env.VUE_APP_IS_SHOW_REGISTER === 'true'
    },
    // 是否显示手机号登录
    isShowPhone () {
      return process.env.VUE_APP_IS_PHONE_LOGIN === 'true'
    },
    useCountdownTime () {
      return `重新发送(${this.countdownTime}) `
    },
    isShowForgetCode () {
      return process.env.VUE_APP_IS_SHOW_CODE === 'true'
    },
    isShowAutoLogin () {
      return process.env.VUE_APP_AUTO_LOGIN === 'true'
    },
    currRouter () {
      return this.$route.path
    },
    ...mapGetters(['isRisk'])
  },
  beforeDestroy () {
    clearInterval(this.timeId)
  },
  watch: {
    countdownTime (val) {
      if (val === 0) {
        // 移除监听，重新赋值
        clearInterval(this.timeId)
        this.countdownTime = 60
        this.isGetCaptcha = false
      }
    },
    $route: {
      immediate: true,
      handler (val) {
        // 钉钉扫码登录
        if (val.params.type && val.params.type === 'dingTalk') {
          const query = val.query
          const { code, state } = query
          if (code && state) {
            this.nailedFormValidate.code = code
            this.nailedFormValidate.state = state
            // openMask('login', '授权登录中，请稍等...')
            dingTalkQrLogin(this.nailedFormValidate).then(data => {
              saveLoginInfo(data)
            }).catch(error => {
              if (error.code && error.code === '1030') {
                message.message.error((error.message || '系统错误') + ',3秒后为你跳转到绑定页', { duration: 3 }, () => {
                  const id = (error.data || {}).id
                  this.$router.replace(`/loginBind/${id}/${1}`)
                })
              } else {
                message.message.error((error.message || '系统错误') + ',3秒后为你跳转到登录页', { duration: 3 }, () => {
                  goLogin()
                })
              }
            }).finally(() => {
              // closeMask('login')
            })
          }
        } else if (val.params.type && val.params.type === 'weChat') {
          const query = val.query
          const { code, state } = query
          if (code && state) {
            this.weChatFormValidate.code = code
            this.weChatFormValidate.state = state
            // openMask('login', '授权登录中，请稍等...')
            weChatLogin(this.weChatFormValidate).then(data => {
              saveLoginInfo(data)
            }).catch(error => {
              if (error.code && error.code === '1030') {
                message.message.error((error.message || '系统错误') + ',3秒后为你跳转到绑定页', { duration: 3 }, () => {
                  const id = (error.data || {}).id
                  this.$router.replace(`/loginBind/${id}/${4}`)
                })
              } else {
                message.message.error((error.message || '系统错误') + ',3秒后为你跳转到登录页', { duration: 3 }, () => {
                  goLogin()
                })
              }
            }).finally(() => {
              // closeMask('login')
            })
          }
        }
      }
    }
  },
  methods: {
    ...mapMutations({
      updateRiskState: STATE_KEY.updateRiskState
    }),
    isDingTalk (val) {
      this.isShowDingTalk = val
    },
    /**
       * 初始
       */
    privateInit () {
      const isRemember = cookieData(COOKIE_KEY.rememberAccount) || false
      this.isRemember = isRemember
      if (isRemember) {
        let user = getCookieItem(COOKIE_KEY.user)
        if (typeOf(user) !== 'undefined') {
          user = JSON.parse(decrypt(user))
          Object.keys(this.formValidate).forEach(item => {
            this.formValidate[item] = user[item] || ''
          })
        }
      } else {
        let userAccount = getCookieItem(COOKIE_KEY.userAccount)
        if (typeOf(userAccount) !== 'undefined') {
          userAccount = JSON.parse(decrypt(userAccount))
          this.formValidate.userAccount = userAccount
        }
      }
      // 获取版本信息
      this.getVersionInfo()
    },
    /**
       * 表单提交
       */
    handleSubmit (name) {
      // 开启加载
      this.loading = true
      // 获取公钥
      getRsaPublicKey().then(({ data }) => {
        return data
      }).then(data => {
        let userAccount = this.formValidate.userAccount
        // 去空格
        userAccount = userAccount.replace(/(^\s*)|(\s*$)/g, '')
        const rsaKey = data.rsaKey
        // 加密
        const publicKey = data.publicKey
        const enc = new JSEncrypt()
        enc.setPublicKey(publicKey)
        let password = this.formValidate.password
        password = enc.encrypt(password)
        // 登录
        return login({ userAccount, rsaKey, password })
      }).then(data => {
        // 存储是否登录状态
        setCookieItem(COOKIE_KEY.rememberAccount, this.isRemember)
        // 加密用户信息并存储到cookie(设置存储时效为3天)
        if (this.isRemember) {
          setCookieItem(COOKIE_KEY.user, encrypt(JSON.stringify(this.formValidate)), { expires: 3 })
        }
        saveLoginInfo(data)
        this.updateRiskState(false)
        this.loading = false
      }).catch((error) => {
        if (typeOf(error.code) !== 'undefined' && error.code === '1010') {
          this.updateRiskState(true)
        }
        message.message.error(error.message ? error.message : '系统错误')
        // 关闭加载
        this.loading = false
        this.codeIsShow = false
        this.tsetViewParams.flag = false
      })
    },
    /**
       * 点击注册/忘记密码等触发
       */
    handleRouterOperate (path = '/register') {
      if (this.currRouter !== path) {
        this.$router.push({ path })
      }
    },
    /**
       * 获取验证码
       */
    getCaptcha () {
      this.isGetCaptcha = true
      this.timeId = setInterval(() => {
        this.countdownTime -= 1
      }, 1000)
    },
    /**
     * 验证通过触发
     */
    onSuccess () {
      this.handleSubmit('formValidate')
      // this.msg = '校验成功！'
      // this.login('formValidate')
    },
    onFail () {
      // this.msg = '校验失败请重试'
      // this.codeIsShow = false
    },
    onRefresh () {
      this.msg = ''
    },
    /**
     * 点击登录时触发
     */
    login (name) {
      this.$refs[name].validate(valid => {
        // 校验通过
        if (valid) {
          if (this.isRisk) {
            this.tsetViewParams.flag = true
          } else {
            this.handleSubmit('formValidate')
          }
          // this.tsetViewParams.flag = true
        } else {
          message.message.remove()
          message.message.error('输入格式错误，请检查后重试')
          // this.codeIsShow = false
        }
      })
    },
    /**
       * 获取版本信息
       */
    getVersionInfo () {
      getNewVersion().then(res => {
        const { data } = res
        if (data !== undefined && typeOf(data.versionCode) !== 'null') {
          let version = cookieData(COOKIE_KEY.version)
          if (typeOf(version) === 'undefined') {
            // 没有版本信息，添加版本信息
            version = { versionCode: data.versionCode, isShow: false }
            setCookieItem(COOKIE_KEY.version, version)
          } else if (version.versionCode !== data.versionCode) {
            // 版本不一，强制推送
            version = { versionCode: data.versionCode, isShow: true }
            setCookieItem(COOKIE_KEY.version, version)
            this.viewParams.flag = true
            this.viewParams.title = `版本更新【${data.versionCode}】`
            this.contentArr = data.updateIntro.split('\n')
          } else if (version.isShow) {
            /* 未关闭推送，继续推送 */
            this.viewParams.flag = true
            this.viewParams.title = `版本更新【${data.versionCode}】`
            this.contentArr = data.updateIntro.split('\n')
          }
        }
      })
    },
    /**
       * 点击版本信息不在提示触发
       */
    handleCancelModal () {
      const version = cookieData(COOKIE_KEY.version) || {}
      version.isShow = false
      setCookieItem(COOKIE_KEY.version, version)
    },
    /**
     * 用户点击钉钉时触发
     */
    handleClickDing () {
      this.isClickDing = true
    }
  },
  components: {
    LayOutLogin: () => import('./LayOutLogin')
  }
}
</script>

<style scoped lang="scss">
  @import "../../assets/styles/scss/mixin";
  .login-no-test{
    width: 100%;
    height: 100%;
  }
  /deep/ .ivu-input {
    border-radius: 0px;
    border: 1px solid rgba(230, 230, 230, 1);
    height: 50px;
  }

  .ivu-form {
    margin-top: 70px;
  }

  .form-box {
    margin-top: 39px;
  }

  .ivu-btn {
    border-radius: 0px;
    height: 50px;
  }

  .ivu-form-item {
    margin-bottom: 40px;
  }

  .form-item-other {
    /deep/ .ivu-form-item-content {
      line-height: 0;
      @include flexMixer(space-between);
      color: #B3B3B3;
    }
  }

  /deep/ .form-item-captcha {
    .ivu-input-suffix {
      width: auto;
      color: #396AFE;
      margin-right: 16px;
      line-height: 50px;
      cursor: pointer;
    }
  }

  .ivu-form-btn {
    margin-bottom: 0;
  }

  /deep/ .form-other-login {
    margin-bottom: 0;
    height: 50px;
    cursor: pointer;
    /deep/ .ivu-form-item-content {
      height: 100%;
      width: 100%;
      @include flexMixer(space-between);
      color: #B3B3B3;
    }
  }

  .code-box {
    position: absolute;
    z-index: 99;
    top: -230px;
    left: 5px;
    width: 310px;
    background: #c3c3c3;

  }
  .verification-model{
    /deep/ .ivu-modal-body{
      padding: 0 0 10px;
    }
    /deep/ .slide-verify-slider{
      width: 310px;
    }
  }
</style>
